package com.test.clyq.daoImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.dao.DataAccessException;

import com.test.clyq.dao.VisitLogsDao;
import com.test.clyq.entity.VisitLogs;
import com.test.clyq.entity.VisitLogsCountResult;
import com.test.dao.hibernate.BaseDaoHibernate;
import com.test.util.FormatExceptionStack;
import com.test.util.Pagination;

/**
 * VisitLogsDaoHibernate. <br>
 * 用户访问管理.
 * <p>
 * Copyright: Copyright (c) 2010-3-17 下午04:30:46
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: liuxl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
@SuppressWarnings("unchecked")
public class VisitLogsDaoHibernate extends BaseDaoHibernate implements VisitLogsDao {

	/**
	 * 获取一个下载文件
	 */
	public VisitLogs getOneVisitLog(Long id) {
		this.log.info("根据日志ID获得下载文件start");
		try {
			VisitLogs log = (VisitLogs) getItem(VisitLogs.class, id);
			if (log != null) {
				this.log.info("根据日志ID获得下载文件end");
				return log;
			} else {
				this.log.info("根据日志ID获得下载文件end");
				return new VisitLogs();
			}

		}
		catch (DataAccessException e) {
			this.log.error("[VisitLogs]getOneVisitLog发生错误！\n" + FormatExceptionStack.formatException(e));
			return new VisitLogs();
		}
	}

	/**
	 * 通过分页获取下载文件
	 * 
	 * @param pagination
	 * @return
	 */
	public List<VisitLogs> getVisitLogByPage(Pagination pagination) {
		this.log.info("获得日志列表start");
		String sql = "from VisitLogs";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*) " + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得日志列表end");
				return list;
			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<VisitLogs>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[VisitLogs]getVisitLogByPage发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<VisitLogs>();
		}
		finally {
			session.close();
		}
	}

	// TODO
	public List<VisitLogsCountResult> getVisitLogByTime(String startTime, String endTime, String searcyType, String keywords) {
		String sql = "";
		if ("phone".equals(searcyType)) {
			sql = "select mobile_num,count(*) num_count from t_visitlogs t where t.visit_time>" + startTime + " and t.visit_time<" + endTime;
			if (keywords != null && !"".equals(keywords)) {
				sql = sql + " and t.mobile_num like '%" + keywords + "%'";
			}
			sql = sql + " group by t.mobile_num order by num_count desc";
		} else if ("phone_image".equals(searcyType)) {
			sql = "select substr(t.visit_time,0,8),count(*) from t_visitlogs t where t.visit_time>" + startTime + " and t.visit_time<" + endTime
			        + " and t.mobile_num='" + keywords + "' group by substr(t.visit_time,0,8)";

		} else if ("title_image".equals(searcyType)) {
			sql = "select substr(t.visit_time,0,8),count(*) from t_visitlogs t where t.visit_time>" + startTime + " and t.visit_time<" + endTime
			        + " and t.entity_title='" + keywords + "' group by substr(t.visit_time,0,8)";
		} else if ("title".equals(searcyType)) {
			sql = "select entity_title,count(*) num_count from t_visitlogs t where t.visit_time>" + startTime + " and t.visit_time<" + endTime;
			if (keywords != null && !"".equals(keywords)) {
				sql = sql + " and t.entity_title like '%" + keywords + "%'";
			}
			sql = sql + " group by t.entity_title order by num_count desc";
		} else {
			sql = "select substr(t.visit_time,0,8),count(*) from t_visitlogs t where t.visit_time>" + startTime + " and t.visit_time<" + endTime
			        + " group by substr(t.visit_time,0,8)";
		}

		System.out.println("==>" + sql);

		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		List<VisitLogsCountResult> l = new ArrayList<VisitLogsCountResult>();
		try {
			Query query = session.createSQLQuery(sql);
			List list = query.list();
			int size = list.size();
			for (int i = 0; i < size; i++) {
				VisitLogsCountResult vo = new VisitLogsCountResult();
				Object[] object = (Object[]) list.get(i);
				vo.setCategoryName((String) object[0]);

				java.math.BigDecimal mmBigDecimal = (java.math.BigDecimal) object[1];
				long count = mmBigDecimal.longValue();
				vo.setCount(count);
				vo.setCode(searcyType);

				l.add(vo);
			}
		}
		catch (Exception e) {
			this.log.error("[VisitLogsCountResult]getVisitLogByTime发生错误！\n" + FormatExceptionStack.formatException(e));
		}
		finally {
			session.close();
		}
		return l;
	}

	public void saveOrUpdateVisitLogs(VisitLogs logs) {
		this.log.info("新增用户访问日志start");
		try {
			saveObject(logs);
			this.log.debug("新增用户访问日志成功");
			this.log.info("新增用户访问日志end");
		}
		catch (DataAccessException e) {
			this.log.error("[VisitLogs]saveOrUpdateVisitLogs发生错误！\n" + FormatExceptionStack.formatException(e));
		}

	}

}
